<?php

include_once('lib/parvis.constants.php');
require_once ('lib/class.http.php');
require_once ('lib/dump.php');
require_once ('lib/class.urls.php');

// Retrouver la langue de l'URL
$langage = urls::getLangNum();

$api = new Http();
$api->debug = $debug;

//$url = 'http://www.parvis.ch/cgi-bin/cgiip.exe/WService=wsbroker1/tbr_login.w';
$url = sprintf('%stbr_login.w', WEBSPEED);

$api->useCurl(false);

if (empty($_POST)) {
	// 1er appel: GET
    $api->setMethod('GET');


    $api->addParam('lang', $langage);
    $api->addParam('langue', $langage);
    $api->addParam('id', $_GET['id']);
    $api->addParam('retour', ($_GET['retour']));

} else {
	// Appels suivants (via un des boutons de l'interface)
    $api->setMethod('POST');

    // Les paramètres de POST sont redécodés en ISO
    foreach ($_POST as $key => $post) {
	    $param = utf8_decode($_POST[$key]);

	    $api->addParam($key, $param);
	}

    $api->addParam('lang', $langage);
    $api->addParam('langue', $langage);
}


$api->useCookie(true);
$api->saveCookie(true);
$api->addCookie('SessionId', $_COOKIE['SessionId']);

//$api->addCookie('InterNou', $_COOKIE['InterNou']);


$api->execute($url);

$cookies = $api->_cookies;

if ($debug) {
	dump($cookies, 'Cookies retourné par le serveur');

	dump($cookies[0]['value'], 'value');
}

if (!empty($cookies[0])) {
	// Stockage "local" du cookie retourné par le serveur
	if ($cookies[0]['name'] == 'InterNou') {
		setcookie('InterNou', $cookies[0]['value'], COOKIES_TIME, COOKIES_PATH);
	}
	if ($cookies[0]['name'] == 'SessionId') {
		setcookie('SessionId', $cookies[0]['value'], COOKIES_TIME, COOKIES_PATH);
	}
	if ($cookies[0]['name'] == 'TempCli') {
		setcookie('TempCli', $cookies[0]['value'], COOKIES_TIME, COOKIES_PATH);
	}	
}

echo ($api->error) ? $api->error : utf8_encode($api->result);

if (!empty($_POST) && (strpos($_SERVER['QUERY_STRING'],'login') !== false || strpos($_SERVER['QUERY_STRING'],'logout') !== false)) {
	if(substr_count($_SERVER['HTTP_REFERER'],"/") > 3){
		drupal_goto("<front>");
	}else{
		drupal_goto($_SERVER['HTTP_REFERER']);
	}
}

?>
